package com.azt.novel.search.service.impl;

import com.azt.novel.book.dao.entity.BookInfo;
import com.azt.novel.book.dao.mapper.BookInfoMapper;
import com.azt.novel.book.dto.req.BookSearchReqDto;
import com.azt.novel.book.dto.resp.BookEsRespDto;
import com.azt.novel.book.dto.resp.BookInfoRespDto;
import com.azt.novel.common.resp.PageRespDto;
import com.azt.novel.common.resp.RestResp;
import com.azt.novel.search.constant.EsConsts;
import com.azt.novel.search.service.SearchService;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


@Service
@RequiredArgsConstructor
@Slf4j
public class SearchServiceImpl implements SearchService {


    @Resource
    private BookInfoMapper bookInfoMapper;

    @Override
    public RestResp<PageRespDto<BookInfoRespDto>> searchBooks(BookSearchReqDto condition) {
        //分页
        Page<BookSearchReqDto> page = new Page<>();
        page.setCurrent(condition.getPageNum());
        page.setSize(condition.getPageSize());
        //根据分页查询书籍
        List<BookInfo> bookInfos = bookInfoMapper.searchBooks(page, condition);
        //获取复合条件的总书籍量
        List<BookInfoRespDto> bookInfoRespDtos = new ArrayList<>();
        bookInfos.forEach(bookInfo -> {
            BookInfoRespDto bookInfoRespDto = BookInfoRespDto.builder()
                    .id(bookInfo.getId())
                    .bookName(bookInfo.getBookName())
                    .categoryId(bookInfo.getCategoryId())
                    .categoryName(bookInfo.getCategoryName())
                    .authorId(bookInfo.getAuthorId())
                    .authorName(bookInfo.getAuthorName())
                    .wordCount(bookInfo.getWordCount())
                    .lastChapterName(bookInfo.getLastChapterName())
                    .build();
            bookInfoRespDtos.add(bookInfoRespDto);
        });
        PageRespDto<BookInfoRespDto> bookInfoRespDtoPageRespDto = new PageRespDto<>(
                condition.getPageNum(),condition.getPageSize(),page.getTotal(),
                bookInfoRespDtos
        );

        return RestResp.ok(bookInfoRespDtoPageRespDto);
    }
}
